package com.woniuxy.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.woniuxy.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Slf4j
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        Subject subject = getSubject(request, response);
        String[] perms = (String[]) mappedValue;

        boolean isPermitted = true;
        if (perms != null && perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else {
                if (!subject.isPermittedAll(perms)) {
                    isPermitted = false;
                }
            }
        }
        response.setContentType("application/json");
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            if (isPermitted) {
                //获取当前访问的url
                String url = ((HttpServletRequest)request).getRequestURI().toString();
                //如果是访问本项目的url就放行
                if (url.contains("adminUser")){
                    return true;
                }
                log.info("权限认证通过");
                response.getWriter().write(objectMapper.writeValueAsString(ResponseResult.SUCCESS));
            } else {
                ResponseResult<Void> result = new ResponseResult<>(403, "会话失效，重新登录");
                response.getWriter().write(objectMapper.writeValueAsString(result));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return isAccessAllowed(request, response, mappedValue);
    }
}
